/**
 * 版本号 2017-12-20 08:16
 * @param url
 * @returns {_XAJA}
 * @constructor
 */

window.XAJA = function (url) {
  return new _XAJA(url);
}

window.XAJAConfirmProxy = function (callback) {

  //使用配置的confirm插件

  return new _XAJAConfirmProxy(callback);

}

function _XAJAConfirmProxy(callback) {
  this.callback = callback;

}

_XAJAConfirmProxy.prototype = {

  setMsg: function (msg) {
    this.msg = msg;
    return this;
  },

  exec: function () {
    var _this = this;
    if (this.msg) {
      XAJAConfig.confirmPlugin(this.msg, function () {
        _this.callback();
      });
    } else {
      XAJAConfig.confirmPlugin(undefined, function () {
        _this.callback();
      });
    }

  }


}

//用户自定义配置
XAJAUserConfig = {}

//默认的所有配置
XAJAConfig = {
  successKey: "success",
  successValue: true,
  unSuccessValue: false,
  successValueBooleanType: true,
  successMsgKey: "msg",
  isDo401: true,
  successTipPlugin: function (msg) {
    $.toptip(msg, 'success');
  }
  ,
  confirmPlugin: function (msg, callback) {
    swal({
      title: '操作提示',
      text: msg ? msg : "确定执行该操作吗？",
      type: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      cancelButtonText: "取消",
      confirmButtonText: '是的，确定执行！'
    }).then(function () {
      callback();
    })
  }
  ,
//默认执行的失败回调方法
  failTipPlugin: function (msg) {
    $.toptip(msg, 'error');
  }
  ,

  //默认before之前做的事
  beforePlugin: function () {
  }
  ,
  //默认after之前做的事
  afterPlugin: function () {
  }
  ,

//默认执行的错误回调方法
  innormalTipPlugin: function (xhr) {
    $.toptip("状态码：" + xhr.status, 'error');

  }
  ,

//默认不成功的回调方法
  unSuccessTipPlugin: function (result) {


    $.toptip(result.msg, 'error');

  }
  ,

//401
  do401Plugin: function (result) {
    //跳转

  }
  ,

  webCodeMsg: {
    404:
      "请求链接404错误",
    401:
      "未授权",
    500:
      "后台出错",
    403:
      "没有权限"
  }


}


//参数可能为url，也可能为form表单的$元素
function _XAJA(url) {
  this.url = url;
  //this.isExec = true;
}

//请求的结果只可能有三种，一种是成功，一种是非成功，一种是失败(404，401，500等异常)

////////////////////这条线开始是更新的核心////////////////////////

_XAJA.prototype = {

  //是否自动开启确认操作
  confirm: function (callback) {
    this._confirm = callback;
    if (this.successor) {
      this.successor.handle()
    }
  },
  async: function () {
    this._async = false;
    return this;
  },

  noUseAB: function () {
    this._noUseAB = true;
    return this;
  },

  //传入参数
  data: function (data) {
    this._data = data;
    return this;
  },
  contentType: function (contentType) {
    // this.contentType = "application/x-www-form-urlencoded";
    this._contentType = contentType;
    return this;
  },


  //请求前执行的函数(例如显示进度加载条什么的)
  before: function (callback) {
    this.beforeFUN = callback;
    return this;
  },

  //请求后执行的函数（例如隐藏进度条什么的）
  after: function (callback) {
    this.afterFUN = callback;
    return this;
  },
  //成功时执行的函数
  success: function (callback) {
    this.successFUN = callback;
    return this;
  },

  //成功时返回所有数据
  success2: function (callback) {
    this.successFUN2 = callback;
    return this;
  },

  //成功后执行的函数（例如关闭进度加载条）
  afterSuccess: function (callback) {
    this.afterSuccessFUN = callback;
    return this;
  },


  //统一请求错误的处理
  innormal: function (callback) {

    this.innormalFUN = callback;
    return this;

  },
  //之后
  afterInnormal: function (callback) {

    this.afterInnormalFUN = callback;
    return this;

  },


  //非成功时执行的函数
  unSuccess: function (callback) {
    this.unSuccessFUN = callback;
    return this;
  },

  //非成功前执行函数（没用）
  beforeUnSuccess: function (callback) {
    this.beforeUnSuccessFUN = callback;
    return this;
  },

  //非成功后执行函数（例如关闭进度条什么的）
  afterUnSuccess: function (callback) {
    this.afterUnSuccessFUN = callback;
    return this;
  },


  //请求服务器后台回应失败的操作（不包括401，404等问题）
  doUnsuccess: function (result) {

    if (this.unSuccessFUN) {
      this.unSuccessFUN(result);
    } else {

    }

    if (this.afterUnSuccessFUN) {
      this.afterUnSuccessFUN(result);
    } else {

    }

  },


  unifyHandle: function (callback) {
    this.unifyHandleFUN = callback;
    return this;
  },


  afterUnifyHandle: function (callback) {

    this.afterUnifyHandleFUN = callback;
    return this;

  },


  //一切除了成功之外的任何客户不愿想看到的处理
  doUnifyHandle: function (obj) {


    var msg;
    if (obj.status) {
      msg = XAJAConfig.webCodeMsg[obj.status]
    } else {
      msg = obj.msg;
    }

    if (this.unifyHandleFUN) {
      this.isDoUnifyHandle = true;
      this.unifyHandleFUN(msg);
    } else {

    }
    if (this.afterUnifyHandleFUN) {
      this.afterUnifyHandleFUN(msg);
    } else {

    }


  },


  //异常处理
  doInnormal: function (xhr) {

    if (XAJAConfig.isDo401 == true) {
      //优先处理401
      if (xhr.status == 401) {
        XAJAConfig.do401Plugin(xhr);
        return;
      }
    }


    //先看看是够客户端已经开启了统一处理
    this.doUnifyHandle(xhr);
    //先看看是够客户端已经开启了统一处理
    if (this.isDoUnifyHandle) {
      return;
    }

    if (this.innormalFUN) {
      this.innormalFUN(xhr);
    } else {
      XAJAConfig.innormalTipPlugin(xhr);
    }

    if (this.afterInnormalFUN) {
      this.afterInnormalFUN(xhr);
    } else {
      //执行配置方法
    }
  },

  //正常处理（成功和非成功）
  doNormal: function (result) {

    //console.info("请求得到的数据:" + JSON.stringify(result));

    if (result[XAJAConfig.successKey] == XAJAConfig.successValue) {
      //操作成功
      if (this.successFUN2) {
        if (result) {
          this.successFUN2(result)
        }
      } else {
        if (this.successFUN) {
          //执行用户自定义方法
          if (result.data) {
            this.successFUN(result.data)
          } else {
            this.successFUN(result.msg);
          }
        } else {
          // 执行默认方法
          XAJAConfig.successTipPlugin(result[XAJAConfig.successMsgKey]);
        }
      }
      if (this.afterSuccessFUN) {
        if (result.data) {
          this.afterSuccessFUN(result.data)
        } else {
          this.afterSuccessFUN(result.msg);
        }
      } else {
        //执行配置方法

      }
    } else if (result[XAJAConfig.successKey] == XAJAConfig.unSuccessValue) {
      //操作非成功

      this.doUnifyHandle(result);
      //先看看是够客户端已经开启了统一处理
      if (this.isDoUnifyHandle) {
        return;
      }

      if (this.beforeUnSuccessFUN) {
        this.beforeUnSuccessFUN(result);
      } else {
        //执行配置方法

      }
      if (this.unSuccessFUN) {
        //执行用户自定义方法
        if (result.data) {
          this.unSuccessFUN(result.data)
        } else {
          this.unSuccessFUN(result.msg);
        }
      } else {
        XAJAConfig.unSuccessTipPlugin(result);
      }
      if (this.afterUnSuccessFUN) {
        this.afterUnSuccessFUN(result);
      } else {
        //执行配置方法

      }
    } else {
      throw "请求成功但无对应json相应，请检查是否出现重定向或者对应参数问题";
    }
  },


  doBefore: function () {
    if (this.beforeFUN) {
      this.beforeFUN();
    } else {

      if (!this._noUseAB) {
        XAJAConfig.beforePlugin();

      }

    }
  },


  doAfter: function () {
    if (this.afterFUN) {
      this.afterFUN();
    } else {

      if (!this._noUseAB) {
        XAJAConfig.afterPlugin();

      }


    }
  },


  confirmGet: function () {
    if (_this._confirm) {

    }
  },


  get: function () {

    var _this = this;
    var contentType = _this._contentType;
    var async = _this._async;

    if (!contentType) {
      contentType = "application/json; charset=utf-8";
    }
    if (!async) {
      async = true;
    }

    $.ajax({
      beforeSend: this.doBefore(),
      url: this.url,
      type: "GET",
      async: async,
      data: _this._data,
      contentType: contentType,
      dataType: "json",
      xhrFields: {withCredentials: true},
      crossDomain: true,
      success: function (result) {
        _this.doNormal(result);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {

        _this.doInnormal(XMLHttpRequest);


      },
      complete: function () {
        _this.doAfter();
      }
    });
  },


  post: function () {

    var _this = this;
    var contentType = _this._contentType;

    if (!contentType) {
      contentType = "application/json; charset=utf-8";
    }

    $.ajax({
      beforeSend: this.doBefore(),
      url: this.url,
      type: "POST",
      data: _this._data,
      contentType: contentType,
      dataType: "json",
      xhrFields: {withCredentials: true},
      crossDomain: true,
      success: function (result) {
        _this.doNormal(result)
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        _this.doInnormal(XMLHttpRequest);
      },
      complete: function () {
        _this.doAfter();
      }
    });
  },


  formData: function () {

    var _this = this;


    $.ajax({
      beforeSend: this.doBefore(),
      url: this.url,
      type: "POST",
      data: _this._data,
      contentType: false,
      processData: false,
      xhrFields: {withCredentials: true},
      crossDomain: true,
      success: function (result) {
        _this.doNormal(result)
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        _this.doInnormal(XMLHttpRequest);
      },
      complete: function () {
        _this.doAfter();
      }
    });
  },


  form: function () {

    var _this = this;
    var options = {
      xhrFields: {withCredentials: true},
      crossDomain: true,
      beforeSend: this.doBefore(),
      success: function (result) {
        _this.doNormal(result)
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        _this.doInnormal(XMLHttpRequest);
      },
      complete: function () {
        _this.doAfter();
      }
    };
    this.url.ajaxSubmit(options);

  }


}


///////////////////以下部分是工具类///////////////////////

UrlUtils = {
  GetQueryString: function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg); //获取url中"?"符后的字符串并正则匹配
    var context = "";
    if (r != null)
      context = r[2];
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
  }
}


//扩展这个serializeArray，让其支持得到未选择的checkbox
$.fn.serializeAll = function () {

  var formObj = this.serializeArray();
  formObj = formObj.concat(
    jQuery('input[type=checkbox]:not(:checked)', this).map(
      function () {
        return {
          "name": this.name,
          "value": "0"
        }
      }).get()
  );
  return formObj;
};

$.extend({

  dateUtils: {
    second2Time: function (second_time) {
      second_time = parseFloat(second_time) / 1000;
      var time = parseInt(second_time) + "秒";
      if (parseInt(second_time) > 60) {

        // var second = parseInt(second_time) % 60;
        var min = parseInt(second_time / 60);
        time = min + "分";

        if (min > 60) {
          min = parseInt(second_time / 60) % 60;
          var hour = parseInt(parseInt(second_time / 60) / 60);
          time = hour + "小时" + min + "分";

          if (hour > 24) {
            hour = parseInt(parseInt(second_time / 60) / 60) % 24;
            var day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
            time = day + "天" + hour + "小时" + min + "分";
          }
        }

      }

      return time;
    },

    formatter: function (date) {
      date = new Date(date);

      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      var d = date.getDate();

      var h = date.getHours();
      var mi = date.getMinutes();
      var s = date.getSeconds();

      return y + '-' + (m < 10 ? ('0' + m) : m) + '-'
        + (d < 10 ? ('0' + d) : d) + " " + (h < 10 ? ('0' + h) : h) + ":" + (mi < 10 ? ('0' + mi) : mi) + ":" + (s < 10 ? ('0' + s) : s);
    },
    formatterToDate: function (date) {
      date = new Date(date);

      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      var d = date.getDate();


      return y + '-' + (m < 10 ? ('0' + m) : m) + '-'
        + (d < 10 ? ('0' + d) : d);
    },
    addDay: function (date, amount) {
      date.setDate(date.getDate() + amount);

      return date;
    },

    stampToTime: function (timestamp) {
      //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var date = new Date(timestamp);
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = date.getDate() + ' ';
      var h = date.getHours() + ':';
      var m = date.getMinutes() + ':';
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    stampToDate: function (timestamp) {
      var newDate = new Date();  //实例化一个Date对象
      newDate.setTime(timestamp); //设置Date对象的时间为时间戳的时间
      return newDate;
    },
    compare: function (date1, date2) {

      if (date1.getTime() > date2.getTime()) {
        return true;
      } else {
        return false;

      }


    }
  },

  browerUtils: {
    isWeiXin: function () {
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
      } else {
        return false;
      }
    }
  }


})


MYUtils = {

  isNotEmpty: function (value) {
    if (!value) {
      return false;
    } else if (value == null) {
      return false;
    } else if (value == "") {
      return false;
    } else {
      return true;
    }
  },

  isEmpty: function (value) {
    if (!value) {
      return true;
    } else if (value == null) {
      return true;
    } else if (value == "") {
      return true;
    } else {
      return false;
    }
  }

}



